package DatabaseManaging;

import java.io.PrintWriter;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import Autodesk.ParseLogs;
import DatabaseManaging.Models.LangChan;
import DatabaseManaging.Models.LanguageBuilder;

public class LanguageChannelDatabaseChecker extends DatabaseChecker{
	private static Logger logger = Logger.getLogger(ParseLogs.class);
	public LanguageChannelDatabaseChecker() {
		super(new JdbcLanguageDao());
	}
	
	@Override
	public void checkDatabase(ArrayList<String> parciaList,
			String documentLine, PrintWriter pw, String[] docLineSp,
			String productList) {

	}

	@Override
	public Object getElement(String elementName) {
		LangChan language=LanguageBuilder.build(elementName);		
		return language;
	}

	@Override
	public ArrayList<Object> findEqualsName(Object element) {
		LangChan lang=(LangChan) element;
		return this.getJdbc().findElementby(lang.getName());
	}

	@Override
	public void InsertIfitIsNOTRepeated(ArrayList<Object> listDBWithEqName,
			Object elementToInsert) {
		LangChan lang=(LangChan) elementToInsert;
		if(!isRepeatedInDB(listDBWithEqName, lang)){
			this.getJdbc().insertElement(lang);
			logger.info("Inserted:"+lang);
		}
		
	}
	public boolean isRepeatedInDB(ArrayList<Object> listDBWithEqName,LangChan languageFromList) {
		boolean isRepeated=false;
		LangChan langList=(LangChan) languageFromList;
		for(int i=0;i<listDBWithEqName.size();i++){
			LangChan langDB=(LangChan)listDBWithEqName.get(i);
			if(langList.getName().equals(langDB.getName())) {
				isRepeated=true;
			}
		}
		return isRepeated;
	}
	@Override
	public void updateDatabase(ArrayList<Object> listDBWithEqName,
			Object languageFromList) {
		LangChan langList=(LangChan) languageFromList;
		for(int i=0;i<listDBWithEqName.size();i++){
			LangChan langChan1=(LangChan)listDBWithEqName.get(i);
			LangChan langChanUpdated=new LangChan(langChan1);
			langChanUpdated=addAbbsToElement(langChanUpdated, langList);
			if(!(langChan1.getAbbs().equals(langChanUpdated.getAbbs()))){
				this.getJdbc().updateAbbsByName(Long.toString(langChanUpdated.getId()), langChanUpdated.getAbbs());
				logger.info("Updated: "+langChanUpdated);
			}
		}
	}

	@Override
	public Object updateRegister(ArrayList<Object> listDBWithEqName,
			Object element) {
		LangChan prdList=(LangChan) element;
		for(int i=0;i<listDBWithEqName.size();i++){
			LangChan prdDB=(LangChan)listDBWithEqName.get(i);
			prdList=addAbbsToElement(prdList, prdDB);
		}
		return prdList;
	}

	private LangChan addAbbsToElement(LangChan elementToAdd, LangChan elementToCheck) {
		for(int j=0;j<elementToCheck.getAbbs().size();j++){//ITER BETWEEN ABBS
			if(!elementToAdd.getAbbs().contains(elementToCheck.getAbbs().get(j))){
				elementToAdd.getAbbs().add(elementToCheck.getAbbs().get(j));
			}
		}
		return elementToAdd;
	}

}
